//
//  NotificationControl.swift
//  JMIMSDK
//
//  Created by AlbertYuan on 2022/10/24.
//  通知控制

import Foundation
import UIKit

public struct NotificationControl{

    //回调
    public typealias opnestate = ((_ state:Bool)->())?
    public typealias opneAction = ((_ state:Bool)->())?

    //权限判断
    public static func notificationOpenState(openState:opnestate = nil){
        //首先判断应用通知是否授权，注意iOS10.0之后方法不一样
        if #available(iOS 10.0, *) {
            UNUserNotificationCenter.current().getNotificationSettings { settings in
                switch settings.authorizationStatus{

                case .notDetermined,.denied:
                    DispatchQueue.main.async {
                        openState?(false)
                    }
                    break
                default:
                    DispatchQueue.main.async {
                        openState?(true)
                    }
                    break
                }
            }
        }
        else{
            if (UIApplication.shared.currentUserNotificationSettings?.types == .none){
                DispatchQueue.main.async {
                    openState?(false)
                }
            }
        }
    }

    //开启弹窗通知
    public static func opentNotificationAlert(title:String? = nil,
                                       message:String? = nil,
                                       cancle:String? = nil,
                                       sure:String? = nil){

        let alertController = UIAlertController(title: title ?? "开启通知",
                                                message: message ?? "开启消息通知,不错过重要拾光!", preferredStyle: .alert)
        let cancelAction = UIAlertAction(title:cancle ?? "取消", style: .cancel, handler: nil)
        alertController.addAction(cancelAction)
        let okAction = UIAlertAction(title:sure ?? "确定", style: .default, handler: {
            action in

            if let url = URL(string: UIApplication.openSettingsURLString), UIApplication.shared.canOpenURL(url) {
                if #available(iOS 10.0, *) {
                    UIApplication.shared.open(url, options: [:], completionHandler: nil)
                } else {
                    // Fallback on earlier versions
                }
            }

        })
        alertController.addAction(okAction)
        k_currentVC.present(alertController, animated: true)
    }


    /// 请求通知权限
    /// - Parameter action: 对应操作
    public static func openNotification(action:opneAction){

        //请求通知权限
        UNUserNotificationCenter.current()
            .requestAuthorization(options: [.alert, .sound, .badge]) {
                (accepted, error) in
                action?(accepted)
            }
        //向APNs请求token
        UIApplication.shared.registerForRemoteNotifications()

    }
    
}


